import React, { Component, createRef } from 'react'
import { withRouter } from 'react-router-dom'
import {} from '@ant-design/icons'
import {Card, message, Spin} from 'antd'
import {connect} from 'react-redux'
import '../../style/home.less'
import echarts from 'echarts'
import { rendeLineChart, renderEchart } from './homeEcharts'
import io  from 'socket.io-client'  //这里注意引入的是socket.io-client，因为在不支持websocket的浏览器中，会自动转换为轮询
import { top3Api } from '../../apis/homeApi'

const mapStateToProps = s => {
    console.log(s)
    return{
        userInfo: s.common.userInfo,
        userRole: s.common.userRole
       
    }
}
let _time = null,
    socket = null  //如上面 time  可以定义在外 也可在state中

@withRouter
@connect(mapStateToProps)
 class Home extends Component {

    state = {
        chatNode: createRef(), //创建虚拟dom节点
        chartobj: null,
        loading: true,
        lineNode: createRef(),
        lineObj: null,
        lineLoading: true,
       
    }
  resizeEvt = () => {
    if(!!_time) { clearTimeout(_time) }
    _time = setTimeout(()=>{
     clearTimeout(_time)
     this.state.chartobj.resize()
     this.state.lineObj.resize()
    },360)
  }

 componentDidMount() {
     //只有这个生命周期可以 setstate
    this.setState({
        chartobj: echarts.init(this.state.chatNode.current),
        lineObj: echarts.init(this.state.lineNode.current)
    }, () =>{
        this.getListData()
        this.state.chartobj.on('click',({name, value}) => {
            message.info(name+ "销售数量为："+ value)
        })
        this.getLineData()
        // 对echarts尺寸进行重新，根据屏幕尺寸变化进行触发,
        //为了避免性能浪费，所以进行防抖处理  在用户停下时再执行事件操作
        
        window.addEventListener('resize',this.resizeEvt, false)
    })
 }
//长链接
 getListData() {
     socket = io('http://www.shuiyue.info:12600')
     //socket = io('ws://www.shuiyue.info:12600')  ws:websocket 协议
     socket.on('connect', () => {
         console.log("连接成功")
         socket.emit('clientEvt', {type: 'getTodayHot'})
     })
     //监听消息 on
     socket.on('serverEvt', obj => {
         if(this.state.loading)  this.setState({loading:false})
         //console.log(obj)
       let  data = [],
            label = []
        for (let it of obj) {
            label.push(it.name)
            data.push(it.nums)
        }
        renderEchart(this.state.chartobj,data,label)

     }) 
 }

 async getLineData() {
    let result = await top3Api()
    if(this.state.lineLoading) this.setState({lineLoading: false})
    if(result.code !== 200) return
    rendeLineChart(this.state.lineObj,result.data)
 }

//在将要被销毁的生命周期进行处理
componentWillUnmount() {
    window.removeEventListener('resize',this.resizeEvt)
    //跳转 其他页面后 我要销毁Echarts对象 --释放空间
    if(!!this.state.lineObj) this.state.lineObj.dispose()
    //跳转页面后，socket 也应当销毁
    if(!!socket)  socket.close()
}


//  轮询
    // getListData() {
    //     let obj = [
    //         {}
    //      ],
    //     data = [],
    //     label = []
    //     for (let it of obj) {
    //         label.push(it.name)
    //         data.push(it.name)
    //     }
    //     renderEchart(this.state.chartobj,data,label)

    //     setTimeout( () => {
    //         this.getListData()
    //     },2000)
    // }
    render() {
        console.log(this)
        return (
        <div className="home-container">
            <div className="line">
                <div className="left">
                    <Card className="no-header" bordered={false} >
                        <p>Card content</p>
                        <p>Card content</p>
                        <p>Card content</p>
                    </Card>
                </div>
                <div className="right">
                    <Card  title="今日销售" bordered={false} >
                       <Spin style={{height: '100%'}} spinning={this.state.loading} tip="加载数据中，请稍后...">
                         <div ref={this.state.chatNode} className="chat-box"></div>
                       </Spin>
                    </Card>
                </div>
            </div>
            <div className="line">
                <div className="left"></div>
                <div className="right">
                    
                </div>
            </div>
            <div className="line">
                <Card title="最热三个商品七天销售" bordered={false} >
                    <Spin style={{height: '100%'}} spinning={this.state.lineLoading} tip="加载数据中，请稍后...">
                          <div ref={this.state.lineNode} className="chat-box"></div>
                    </Spin>
                </Card>
            </div>
        </div>
        )
    }
}
export default Home

// <button type="primary" onClick={
//     () => {
//         sessionStorage.clear()
//         console.log(this.props.userRole)
//          this.props.history.push('/login')
//     }
// }>登出</button>